<template>
  <view>
    <view>
      <view class="flex justify-between items-center">
        <text>{{ title }}</text>
        <image
          src="@/static/images/add.png"
          class="w-42rpx h-42rpx"
          @click="onUpload"
          v-if="!disabled&& fileList.length<props.limit"></image>
      </view>
      <text class="text-24rpx text-#fa3534" v-if="!disabled"
        >支持格式: {{ props.extension?.join('、') }},单个文件不超过{{ props.size }}MB。</text
      >
    </view>
    <template v-if="fileList.length">
      <view class="py-24rpx overflow-hidden" v-for="(it, index) in fileList" :key="index">
        <view
          v-if="it.url.endsWith(`.jpg`) || it.url.endsWith(`.png`) || it.url.endsWith(`.jpeg`)"
          class="flex justify-between">
          <view @click="previewImages(it)" class="flex items-center">
            <ImagePreview :src="it.url" :width="80" :height="80" :disabled="true"></ImagePreview>

            <text class="truncate w-500rpx ml-2">{{ file_name[index] || it.name }}</text>
          </view>
          <view>
            <image
              src="@/static/images/del.png"
              class="w-40rpx h-40rpx"
              @click="onDel(index)"
              v-if="!disabled"></image>
          </view>
        </view>
        <view class="flex justify-between" v-else>
          <view class="flex items-center" @click="downloadFile(it)">
            <image src="@/static/images/file.png" class="w-80rpx h-80rpx mr-24rpx"></image>
            <text class="truncate w-500rpx">{{ file_name[index] || it.name }}</text>
          </view>
          <view>
            <image
              src="@/static/images/del.png"
              class="w-40rpx h-40rpx"
              @click="onDel(index)"
              v-if="!disabled"></image>
          </view>
        </view>
      </view>
    </template>
    <!-- <UActionSheet :list="list" v-model="show"  :cancel-btn="true" :safeAreaInsetBottom="true"  @click="onChoose"></UActionSheet> -->
    <u-popup v-model="show" mode="bottom" border-radius="20">
      <view class="h-200rpx flex justify-center flex-col rounded-full">
        <view class="flex justify-center" @click="onChoose(2)">图片</view>
        <view class="flex justify-center" @click="onChoose(1)">文件</view>
      </view>
    </u-popup>
  </view>
</template>
<script lang="ts" setup>
import usePermission from '@/hooks/usePermission'
import { req } from '@/api/req'
import ImagePreview from '@/components/ImagePreview/ImagePreview.vue'
const permission = usePermission()
const uploadUrl = import.meta.env.VITE_APP_BASE_API + 'base/upload_service'
const show = ref(false)
const props = withDefaults(
  defineProps<{
    modelValue?: string | string[] | null
    title?: string
    type?: string
    extension?: string[]
    limit?: number
    size?: number
    fileList?: Record<string, any>[]
    disabled?: boolean
  }>(),
  {
    type: 'all',
    extension: ['.pdf', 'word', 'excel', 'ppt', '.zip', '.png', '.jpeg', '.jpg'],
    limit: 10,
    title: '附件',
    size: 20,
    disabled: false,
  }
)
const extensions = computed(() => {
  const expend = {
    word: ['.doc', '.docx'],
    excel: ['.xls', '.xlsx'],
    ppt: ['.ppt', '.pptx'],
    img: ['.png', '.jpeg', '.jpg'],
  }
  return props.extension.map((it) => expend[it] || it).flat()
})

const file_name = ref<Record<string, any>[]>([])

const emits = defineEmits<{
  (event: 'update:modelValue', value: string | string[]): void
  (event: 'update:fileList', value: { url: string }[]): void
  (event: 'change', value: string | string[], name: string): void
}>()

const list = ref([
  {
    text: '图片',
  },
  {
    text: '文件',
  },
])
const fileList = ref<Record<string, any>[]>([])

watch(
  () => props.modelValue,
  () => {
    if (props.fileList) {
      return
    }
    props.modelValue == '' ? (fileList.value = []) : ''
    if (!props.modelValue?.length) {
      return
    }
    let list: string[]
    if (props.limit === 1) {
      list = Array.isArray(props.modelValue) ? props.modelValue?.slice(0, 1) : [props.modelValue]
    } else {
      list = Array.isArray(props.modelValue) ? props.modelValue : props.modelValue.split(',')
    }

    fileList.value = list.map((url) => ({
      url: `${url}`,
      name: url.split('_')[1] || url,
    }))
    loadFileInfo()
  },
  {
    immediate: true,
    deep: true,
  }
)

function onUpload() {
  show.value = true
}

function onChoose(index: number) {
  if (index == 1) {
    chooseMessageFile()
  } else if (index == 2) {
    chooseMedia()
  }
  show.value = false
}

function chooseMedia() {
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    maxDuration: 30,
    camera: 'back',
    success(res) {
      uni.showLoading({
        title: '上传中...',
        mask: true,
      })
      console.log(res)

      uploadFile(res, 'img')
    },
    fail(error) {
      console.log('选择文件失败', error)
      uni.hideLoading()
    },
  })
}

function chooseMessageFile() {
  uni.chooseMessageFile({
    count: 1,
    type: props.type,
    extension: extensions.value,
    success(res) {
      if (!extensions.value.some((suffix) => res.tempFiles[0].path.endsWith(`${suffix}`))) {
        uni.showToast({ title: '上传格式错误', icon: 'none' })
        return false
      }
      uni.showLoading({
        title: '上传中...',
        mask: true,
      })
      uploadFile(res, 'file')
    },
    fail(error) {
      console.log('选择文件失败', error)
      uni.hideLoading()
    },
  })
}
async function loadFileInfo() {
  const { data } = await req('base/get_file_info_by_url', { file_rel_path: props.modelValue })
  fileList.value.forEach((it, index) => {
    const info = data.find((infos: any) => infos.file_rel_path === it.url)
    if (info) {
      it.name = info.file_name
    }
  })
}

function uploadFile(res: any, type: string) {
  let path = ''
  type == 'img' ? (path = res.tempFiles[0].tempFilePath) : (path = res.tempFiles[0].path)
  uni.uploadFile({
    url: uploadUrl,
    filePath: path,
    name: 'file',
    header: {
      'content-type': 'multipart/form-data',
      token: `Bearer ${permission.token}`,
    },
    formData: {
      'params[is_detail]': 1,
    },
    success(data) {
      const curData = JSON.parse(data.data)
      fileList.value.push({ url: curData.data, name: res.tempFiles[0].name })
      file_name.value.push(res.tempFiles[0].name || res.tempFiles[0].tempFileName)
      console.log(file_name.value)

      upValue()
      uni.hideLoading()
    },
  })
}
async function onDel(index: number) {
  await nextTick
  fileList.value.splice(index, 1)
  file_name.value.splice(index, 1)

  upValue()
}

function upValue() {
  const list = fileList.value.map((it) =>
    it.url?.startsWith(permission.baseUrl) ? it.url.substring(permission.baseUrl.length) : it.url
  )
  const value = Array.isArray(props.modelValue) ? list : list.join()
  emits('update:modelValue', value)
  emits('change', value, file_name.value)
}

function previewImages(it: Record<string, any>) {
  const urlList = fileList.value
    .filter((e) => e.url.endsWith(`.jpg`) || e.url.endsWith(`.png`) || e.url.endsWith(`.jpeg`))
    .map((e) => `${permission.baseUrl}uploads/${e.url}`)
  uni.previewImage({
    current: it.url,
    urls: urlList,
  })
}

function downloadFile(it: Record<string, any>) {
  uni.showLoading({
    title: '预览中...',
    mask: true,
  })
  uni.downloadFile({
    url: `${import.meta.env.VITE_APP_DOWNLOAD_API}${it.url}`, // 网络文档地址
    success: (data) => {
      if (data.statusCode === 200) {
        uni.getFileSystemManager().saveFile({
          tempFilePath: data.tempFilePath, //临时路径
          success: function (res) {
            let suffix = res.savedFilePath.substring(res.savedFilePath.lastIndexOf('.') + 1)
            if (!['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'].includes(suffix))
              return uni.showToast({
                icon: 'none',
                title: '此文件格式不支持预览',
                duration: 2000,
              })
            uni.openDocument({
              showMenu: true,
              fileType: suffix,
              filePath: res.savedFilePath,
              success: function (res) {
                uni.hideLoading()
              },
              fail: (err) => {
                uni.showToast({
                  title: err.errMsg,
                })
              },
            })
          },
        })
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '失败请重新下载',
      })
    },
  })
}
</script>
<style lang="scss"></style>
